{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "11655b37",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "#  序列到序列（seq2seq）\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ea2818a",
   "metadata": {},
   "source": [
    "从一个句子到另一个句子的文本任务（如机器翻译），输入与输出句子的长度可以不同。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36d47747",
   "metadata": {},
   "source": [
    "## 架构"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a148bdd",
   "metadata": {},
   "source": [
    "<img src='seq2seq_0.png' width='800'>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b32daf5",
   "metadata": {},
   "source": [
    "- 编码器是一个RNN，读取输入句子\n",
    "    - 没有输出层\n",
    "    - 最后时间步的隐状态用作解码器的初始隐状态\n",
    "    - 经常是双向RNN\n",
    "- 解码器使用另外一个RNN来输出\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eac987a3",
   "metadata": {},
   "source": [
    "## 训练和推理有区别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d710161",
   "metadata": {},
   "source": [
    "(1)训练模型"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3428f308",
   "metadata": {},
   "source": [
    "<img src='seq2seq_1.png' width = '800'>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3b6676e",
   "metadata": {},
   "source": [
    "(2)推理模型"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1b12484",
   "metadata": {},
   "source": [
    "<img src='seq2seq_0.png' width = '800'>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f384cbe5",
   "metadata": {},
   "source": [
    "## 如何评价序列的好坏"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "187bf146",
   "metadata": {},
   "source": [
    "- $p_n$是预测中所有n-gram的精度\n",
    "    - 标签序列ABCDEF和预测序列ABBCD，则 $p_1 = 4/5$, $p_2 = 3/4$, $p_3 = 1/3$, $p_4 = 0$\n",
    "- BLEU定义\n",
    "\n",
    "<img src='bleu.png' width='800'>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac8337f0",
   "metadata": {},
   "source": [
    "BLEU越大越好，最好是BLEU=1。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d42c6d38",
   "metadata": {},
   "source": [
    "# 代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d6605d68",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:48.126047Z",
     "iopub.status.busy": "2022-07-31T02:47:48.125443Z",
     "iopub.status.idle": "2022-07-31T02:47:49.963373Z",
     "shell.execute_reply": "2022-07-31T02:47:49.962646Z"
    },
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import collections\n",
    "import math\n",
    "import torch\n",
    "from torch import nn\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae503583",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "实现循环神经网络编码器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0e463a08",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:49.967298Z",
     "iopub.status.busy": "2022-07-31T02:47:49.966784Z",
     "iopub.status.idle": "2022-07-31T02:47:49.972741Z",
     "shell.execute_reply": "2022-07-31T02:47:49.972147Z"
    },
    "origin_pos": 6,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Seq2SeqEncoder(d2l.Encoder):\n",
    "    \"\"\"用于序列到序列学习的循环神经网络编码器\"\"\"\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 dropout=0, **kwargs):\n",
    "        super(Seq2SeqEncoder, self).__init__(**kwargs)\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        self.rnn = nn.GRU(embed_size, num_hiddens, num_layers,\n",
    "                          dropout=dropout) # 注意，这里没有输出层，encoder不需要输出层\n",
    "\n",
    "    def forward(self, X, *args): # X的形状： batch_size, num_steps,\n",
    "        X = self.embedding(X)\n",
    "        X = X.permute(1, 0, 2)\n",
    "        output, state = self.rnn(X)\n",
    "        return output, state"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5eaaf9ef",
   "metadata": {},
   "source": [
    "nn.Embedding\n",
    "- 词嵌入，将文字转换为一串数字。词嵌入的过程，就相当于是我们在给计算机制造出一本字典的过程。计算机可以通过这个字典来间接地识别文字。\n",
    "- 词嵌入向量的意思也可以理解成：词在神经网络中的向量表示。\n",
    "\n",
    "参数：\n",
    "- num_embeddings - 词嵌入字典大小，即一个字典里要有多少个词。\n",
    "- embedding_dim - 每个词嵌入向量的大小。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c830a9db",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "上述编码器的实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f1882f0c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:49.976052Z",
     "iopub.status.busy": "2022-07-31T02:47:49.975483Z",
     "iopub.status.idle": "2022-07-31T02:47:49.986517Z",
     "shell.execute_reply": "2022-07-31T02:47:49.985836Z"
    },
    "origin_pos": 10,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([7, 4, 16])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,\n",
    "                         num_layers=2)\n",
    "encoder.eval() # 不让dropout生效\n",
    "X = torch.zeros((4, 7), dtype=torch.long) # 4是batch_size,7是句子长度\n",
    "output, state = encoder(X)\n",
    "output.shape # torch.Size([7, 4, 16]) 对应（num_steps, batch_size, num_hiddens)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b0f1ceee",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:49.989447Z",
     "iopub.status.busy": "2022-07-31T02:47:49.989111Z",
     "iopub.status.idle": "2022-07-31T02:47:49.993757Z",
     "shell.execute_reply": "2022-07-31T02:47:49.993069Z"
    },
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([2, 4, 16])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "state.shape # torch.Size([2, 4, 16])对应（num_layers, batch_size, num_hiddens)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c00bf05",
   "metadata": {},
   "source": [
    "【知识点】tensor.repeat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e77b8150",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([33, 55])"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "a = torch.randn(33,55)\n",
    "a.size()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cba2157e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([33, 110])"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "a.repeat(1,1).size() # torch.Size([33, 55])\n",
    "a.repeat(2,1).size() # torch.Size([66, 55])\n",
    "a.repeat(1,2).size() # torch.Size([33, 110])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce53695f",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "解码器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "03731d86",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:49.996943Z",
     "iopub.status.busy": "2022-07-31T02:47:49.996409Z",
     "iopub.status.idle": "2022-07-31T02:47:50.003188Z",
     "shell.execute_reply": "2022-07-31T02:47:50.002523Z"
    },
    "origin_pos": 18,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class Seq2SeqDecoder(d2l.Decoder):\n",
    "    \"\"\"用于序列到序列学习的循环神经网络解码器\"\"\"\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 dropout=0, **kwargs):\n",
    "        super(Seq2SeqDecoder, self).__init__(**kwargs)\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size) # 如果decoder的词典与encoder不同，就单独设置embedding（比如翻译）\n",
    "        self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers,\n",
    "                          dropout=dropout) # num_hiddens在decoder和encoder是一样的\n",
    "        self.dense = nn.Linear(num_hiddens, vocab_size) # 输出相当于做在vocab_size大小上的分类问题\n",
    "\n",
    "    def init_state(self, enc_outputs, *args): # enc_outputs的结构是[output, state]\n",
    "        return enc_outputs[1] # 这里指encoder输出的state\n",
    "\n",
    "    def forward(self, X, state):\n",
    "        X = self.embedding(X).permute(1, 0, 2) # 把样本的时间步放在最前面\n",
    "        context = state[-1].repeat(X.shape[0], 1, 1) # state[-1]是最后一层的状态,（num_layers, batch_size, num_hiddens)\n",
    "        # print(X.shape) # torch.Size([7, 4, 8])\n",
    "        # print(context.shape) # torch.Size([7, 4, 16])\n",
    "        # print(context)\n",
    "        X_and_context = torch.cat((X, context), 2) # torch.Size([7, 4, 24])\n",
    "        # print(X_and_context)\n",
    "        output, state = self.rnn(X_and_context, state)\n",
    "        output = self.dense(output).permute(1, 0, 2)\n",
    "        return output, state"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31201347",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "实例化解码器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "efdcc315",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1, 9, 5, 8, 3, 1, 4],\n",
       "        [5, 7, 1, 7, 8, 0, 2],\n",
       "        [2, 4, 5, 4, 4, 5, 6],\n",
       "        [2, 9, 1, 5, 8, 5, 6]])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.randint(0,10,(4, 7), dtype=torch.long) # vocab_size=10,所以数上限不能太大\n",
    "X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d90d71cc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.006117Z",
     "iopub.status.busy": "2022-07-31T02:47:50.005692Z",
     "iopub.status.idle": "2022-07-31T02:47:50.015624Z",
     "shell.execute_reply": "2022-07-31T02:47:50.014991Z"
    },
    "origin_pos": 22,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "decoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16,\n",
    "                         num_layers=2)\n",
    "decoder.eval()\n",
    "state = decoder.init_state(encoder(X))\n",
    "output, state = decoder(X, state) # torch.Size([4, 7, 10]), torch.Size([2, 4, 16])\n",
    "output.shape, state.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "696af343",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "通过零值化屏蔽不相关的项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "0f4a1642",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.018552Z",
     "iopub.status.busy": "2022-07-31T02:47:50.018120Z",
     "iopub.status.idle": "2022-07-31T02:47:50.025022Z",
     "shell.execute_reply": "2022-07-31T02:47:50.024440Z"
    },
    "origin_pos": 26,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1, 0, 0],\n",
       "        [4, 5, 0]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def sequence_mask(X, valid_len, value=0):\n",
    "    \"\"\"在序列中屏蔽不相关的项\"\"\"\n",
    "    maxlen = X.size(1)\n",
    "    mask = torch.arange((maxlen), dtype=torch.float32,\n",
    "                        device=X.device)[None, :] < valid_len[:, None]\n",
    "    X[~mask] = value\n",
    "    return X\n",
    "\n",
    "X = torch.tensor([[1, 2, 3], [4, 5, 6]]) # 现在有两个句子\n",
    "sequence_mask(X, torch.tensor([1, 2])) # 第一个句子的有效长度（valid_len)=1,第二个句子valid_len=2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54ec9888",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "我们还可以使用此函数屏蔽最后几个轴上的所有项"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "73028296",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.027943Z",
     "iopub.status.busy": "2022-07-31T02:47:50.027506Z",
     "iopub.status.idle": "2022-07-31T02:47:50.033252Z",
     "shell.execute_reply": "2022-07-31T02:47:50.032629Z"
    },
    "origin_pos": 30,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[ 1.,  1.,  1.,  1.],\n",
       "         [-1., -1., -1., -1.],\n",
       "         [-1., -1., -1., -1.]],\n",
       "\n",
       "        [[ 1.,  1.,  1.,  1.],\n",
       "         [ 1.,  1.,  1.,  1.],\n",
       "         [-1., -1., -1., -1.]]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.ones(2, 3, 4)\n",
    "sequence_mask(X, torch.tensor([1, 2]), value=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "796b27a0",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "通过扩展softmax交叉熵损失函数来遮蔽不相关的预测"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f682389c",
   "metadata": {},
   "source": [
    "填充的部分不参与计算loss。需要给CrossEntropy加个权重，需要的部分权重是1，不需要的部分权重是0。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "e3c9f052",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.036203Z",
     "iopub.status.busy": "2022-07-31T02:47:50.035777Z",
     "iopub.status.idle": "2022-07-31T02:47:50.040461Z",
     "shell.execute_reply": "2022-07-31T02:47:50.039832Z"
    },
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class MaskedSoftmaxCELoss(nn.CrossEntropyLoss):\n",
    "    \"\"\"带遮蔽的softmax交叉熵损失函数\"\"\"\n",
    "    def forward(self, pred, label, valid_len):\n",
    "        weights = torch.ones_like(label) # weights为与label形状一样的为1的张量。\n",
    "        weights = sequence_mask(weights, valid_len)\n",
    "        self.reduction='none'\n",
    "        unweighted_loss = super().forward(\n",
    "            pred.permute(0, 2, 1), label)   # pred.permute(0, 2, 1)是pytorch的要求，把预测的维度放在中间。\n",
    "        weighted_loss = (unweighted_loss * weights).mean(dim=1) # dim=1是对每个句子求平均\n",
    "        return weighted_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a0aa3f0",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "代码健全性检查"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "20354996",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.043348Z",
     "iopub.status.busy": "2022-07-31T02:47:50.042939Z",
     "iopub.status.idle": "2022-07-31T02:47:50.050352Z",
     "shell.execute_reply": "2022-07-31T02:47:50.049552Z"
    },
    "origin_pos": 38,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([2.3026, 1.1513, 0.0000])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "loss = MaskedSoftmaxCELoss()\n",
    "loss(torch.ones(3, 4, 10), torch.ones((3, 4), dtype=torch.long),\n",
    "     torch.tensor([4, 2, 0]))  #(3, 4, 10)，batchsize，time_step,vocab_size\n",
    "# torch.ones((3, 4), dtype=torch.long) 是label\n",
    "# 运行的结果：tensor([2.3026, 1.1513, 0.0000])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0738e75",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "a30d9efc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.053585Z",
     "iopub.status.busy": "2022-07-31T02:47:50.053016Z",
     "iopub.status.idle": "2022-07-31T02:47:50.063087Z",
     "shell.execute_reply": "2022-07-31T02:47:50.062246Z"
    },
    "origin_pos": 42,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):\n",
    "    \"\"\"训练序列到序列模型\"\"\"\n",
    "    def xavier_init_weights(m):\n",
    "        if type(m) == nn.Linear:\n",
    "            nn.init.xavier_uniform_(m.weight)\n",
    "        if type(m) == nn.GRU:\n",
    "            for param in m._flat_weights_names:\n",
    "                if \"weight\" in param:\n",
    "                    nn.init.xavier_uniform_(m._parameters[param])\n",
    "\n",
    "    net.apply(xavier_init_weights)\n",
    "    net.to(device)\n",
    "    optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n",
    "    loss = MaskedSoftmaxCELoss()\n",
    "    net.train()\n",
    "    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n",
    "                     xlim=[10, num_epochs])\n",
    "    for epoch in range(num_epochs):\n",
    "        timer = d2l.Timer()\n",
    "        metric = d2l.Accumulator(2)\n",
    "        for batch in data_iter:\n",
    "            optimizer.zero_grad()\n",
    "            X, X_valid_len, Y, Y_valid_len = [x.to(device) for x in batch] # 注意\n",
    "            bos = torch.tensor([tgt_vocab['<bos>']] * Y.shape[0],\n",
    "                          device=device).reshape(-1, 1) # 给句子一个开头<bos>，然后把后面的元素后移，以实现训练\n",
    "            dec_input = torch.cat([bos, Y[:, :-1]], 1)\n",
    "            Y_hat, _ = net(X, dec_input, X_valid_len) #  X_valid_len这里用不到，注意力机制时用到\n",
    "            l = loss(Y_hat, Y, Y_valid_len)\n",
    "            l.sum().backward()\n",
    "            d2l.grad_clipping(net, 1)\n",
    "            num_tokens = Y_valid_len.sum()\n",
    "            optimizer.step()\n",
    "            with torch.no_grad():\n",
    "                metric.add(l.sum(), num_tokens)\n",
    "        if (epoch + 1) % 10 == 0:\n",
    "            animator.add(epoch + 1, (metric[0] / metric[1],))\n",
    "    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n",
    "        f'tokens/sec on {str(device)}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f66dad35",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "创建和训练一个循环神经网络“编码器－解码器”模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "f392186c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:47:50.066714Z",
     "iopub.status.busy": "2022-07-31T02:47:50.066094Z",
     "iopub.status.idle": "2022-07-31T02:48:32.819636Z",
     "shell.execute_reply": "2022-07-31T02:48:32.818880Z"
    },
    "origin_pos": 45,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loss 0.019, 10280.7 tokens/sec on cpu\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"262.1875pt\" height=\"183.35625pt\" viewBox=\"0 0 262.1875 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2022-12-04T13:18:36.629554</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.5.1, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 183.35625 \n",
       "L 262.1875 183.35625 \n",
       "L 262.1875 0 \n",
       "L 0 0 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 50.14375 145.8 \n",
       "L 245.44375 145.8 \n",
       "L 245.44375 7.2 \n",
       "L 50.14375 7.2 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 77.081681 145.8 \n",
       "L 77.081681 7.2 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"m0585670289\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m0585670289\" x=\"77.081681\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 50 -->\n",
       "      <g transform=\"translate(70.719181 160.398438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 110.754095 145.8 \n",
       "L 110.754095 7.2 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m0585670289\" x=\"110.754095\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 100 -->\n",
       "      <g transform=\"translate(101.210345 160.398438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 144.426509 145.8 \n",
       "L 144.426509 7.2 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m0585670289\" x=\"144.426509\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 150 -->\n",
       "      <g transform=\"translate(134.882759 160.398438)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 178.098922 145.8 \n",
       "L 178.098922 7.2 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m0585670289\" x=\"178.098922\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 200 -->\n",
       "      <g transform=\"translate(168.555172 160.398438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 211.771336 145.8 \n",
       "L 211.771336 7.2 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m0585670289\" x=\"211.771336\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 250 -->\n",
       "      <g transform=\"translate(202.227586 160.398438)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 245.44375 145.8 \n",
       "L 245.44375 7.2 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m0585670289\" x=\"245.44375\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_6\">\n",
       "      <!-- 300 -->\n",
       "      <g transform=\"translate(235.9 160.398438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \n",
       "Q 3050 2419 3304 2112 \n",
       "Q 3559 1806 3559 1356 \n",
       "Q 3559 666 3084 287 \n",
       "Q 2609 -91 1734 -91 \n",
       "Q 1441 -91 1130 -33 \n",
       "Q 819 25 488 141 \n",
       "L 488 750 \n",
       "Q 750 597 1062 519 \n",
       "Q 1375 441 1716 441 \n",
       "Q 2309 441 2620 675 \n",
       "Q 2931 909 2931 1356 \n",
       "Q 2931 1769 2642 2001 \n",
       "Q 2353 2234 1838 2234 \n",
       "L 1294 2234 \n",
       "L 1294 2753 \n",
       "L 1863 2753 \n",
       "Q 2328 2753 2575 2939 \n",
       "Q 2822 3125 2822 3475 \n",
       "Q 2822 3834 2567 4026 \n",
       "Q 2313 4219 1838 4219 \n",
       "Q 1578 4219 1281 4162 \n",
       "Q 984 4106 628 3988 \n",
       "L 628 4550 \n",
       "Q 988 4650 1302 4700 \n",
       "Q 1616 4750 1894 4750 \n",
       "Q 2613 4750 3031 4423 \n",
       "Q 3450 4097 3450 3541 \n",
       "Q 3450 3153 3228 2886 \n",
       "Q 3006 2619 2597 2516 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-33\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_7\">\n",
       "     <!-- epoch -->\n",
       "     <g transform=\"translate(132.565625 174.076563)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \n",
       "L 1159 -1331 \n",
       "L 581 -1331 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "z\n",
       "M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-65\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"61.523438\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-63\" x=\"186.181641\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-68\" x=\"241.162109\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <path d=\"M 50.14375 118.480301 \n",
       "L 245.44375 118.480301 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_14\">\n",
       "      <defs>\n",
       "       <path id=\"md30bc02010\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#md30bc02010\" x=\"50.14375\" y=\"118.480301\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 0.05 -->\n",
       "      <g transform=\"translate(20.878125 122.27952)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <path d=\"M 50.14375 84.464857 \n",
       "L 245.44375 84.464857 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md30bc02010\" x=\"50.14375\" y=\"84.464857\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 0.10 -->\n",
       "      <g transform=\"translate(20.878125 88.264076)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-31\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <path d=\"M 50.14375 50.449413 \n",
       "L 245.44375 50.449413 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_18\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md30bc02010\" x=\"50.14375\" y=\"50.449413\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 0.15 -->\n",
       "      <g transform=\"translate(20.878125 54.248632)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-31\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_19\">\n",
       "      <path d=\"M 50.14375 16.433969 \n",
       "L 245.44375 16.433969 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_20\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#md30bc02010\" x=\"50.14375\" y=\"16.433969\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 0.20 -->\n",
       "      <g transform=\"translate(20.878125 20.233188)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_12\">\n",
       "     <!-- loss -->\n",
       "     <g transform=\"translate(14.798437 86.157813)rotate(-90)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \n",
       "L 2834 2853 \n",
       "Q 2591 2978 2328 3040 \n",
       "Q 2066 3103 1784 3103 \n",
       "Q 1356 3103 1142 2972 \n",
       "Q 928 2841 928 2578 \n",
       "Q 928 2378 1081 2264 \n",
       "Q 1234 2150 1697 2047 \n",
       "L 1894 2003 \n",
       "Q 2506 1872 2764 1633 \n",
       "Q 3022 1394 3022 966 \n",
       "Q 3022 478 2636 193 \n",
       "Q 2250 -91 1575 -91 \n",
       "Q 1294 -91 989 -36 \n",
       "Q 684 19 347 128 \n",
       "L 347 722 \n",
       "Q 666 556 975 473 \n",
       "Q 1284 391 1588 391 \n",
       "Q 1994 391 2212 530 \n",
       "Q 2431 669 2431 922 \n",
       "Q 2431 1156 2273 1281 \n",
       "Q 2116 1406 1581 1522 \n",
       "L 1381 1569 \n",
       "Q 847 1681 609 1914 \n",
       "Q 372 2147 372 2553 \n",
       "Q 372 3047 722 3315 \n",
       "Q 1072 3584 1716 3584 \n",
       "Q 2034 3584 2315 3537 \n",
       "Q 2597 3491 2834 3397 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"27.783203\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"88.964844\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"141.064453\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"line2d_21\">\n",
       "    <path d=\"M 50.14375 13.5 \n",
       "L 56.878233 54.894556 \n",
       "L 63.612716 79.12529 \n",
       "L 70.347198 93.541412 \n",
       "L 77.081681 104.659243 \n",
       "L 83.816164 112.778203 \n",
       "L 90.550647 118.131769 \n",
       "L 97.285129 122.195742 \n",
       "L 104.019612 125.584058 \n",
       "L 110.754095 128.316685 \n",
       "L 117.488578 129.982629 \n",
       "L 124.22306 131.886642 \n",
       "L 130.957543 133.325604 \n",
       "L 137.692026 134.388745 \n",
       "L 144.426509 134.947457 \n",
       "L 151.160991 135.997844 \n",
       "L 157.895474 136.402013 \n",
       "L 164.629957 136.906186 \n",
       "L 171.36444 136.972311 \n",
       "L 178.098922 137.900262 \n",
       "L 184.833405 138.091142 \n",
       "L 191.567888 138.247529 \n",
       "L 198.302371 138.057109 \n",
       "L 205.036853 138.181239 \n",
       "L 211.771336 138.822804 \n",
       "L 218.505819 138.898782 \n",
       "L 225.240302 139.020511 \n",
       "L 231.974784 139.186308 \n",
       "L 238.709267 139.228308 \n",
       "L 245.44375 139.5 \n",
       "\" clip-path=\"url(#p9f9a55f4f9)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 50.14375 145.8 \n",
       "L 50.14375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 245.44375 145.8 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 50.14375 145.8 \n",
       "L 245.44375 145.8 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 50.14375 7.2 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"p9f9a55f4f9\">\n",
       "   <rect x=\"50.14375\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 350x250 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1\n",
    "batch_size, num_steps = 64, 10\n",
    "lr, num_epochs, device = 0.005, 300, d2l.try_gpu()\n",
    "\n",
    "train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\n",
    "encoder = Seq2SeqEncoder(len(src_vocab), embed_size, num_hiddens, num_layers,\n",
    "                        dropout)\n",
    "decoder = Seq2SeqDecoder(len(tgt_vocab), embed_size, num_hiddens, num_layers,\n",
    "                        dropout)\n",
    "net = d2l.EncoderDecoder(encoder, decoder)\n",
    "train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94552e6b",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c58761dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:48:32.823167Z",
     "iopub.status.busy": "2022-07-31T02:48:32.822920Z",
     "iopub.status.idle": "2022-07-31T02:48:32.833096Z",
     "shell.execute_reply": "2022-07-31T02:48:32.832254Z"
    },
    "origin_pos": 48,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,\n",
    "                    device, save_attention_weights=False):\n",
    "    \"\"\"序列到序列模型的预测\"\"\"\n",
    "    net.eval()\n",
    "    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n",
    "        src_vocab['<eos>']]\n",
    "    enc_valid_len = torch.tensor([len(src_tokens)], device=device)\n",
    "    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])\n",
    "    enc_X = torch.unsqueeze(\n",
    "        torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0)\n",
    "    enc_outputs = net.encoder(enc_X, enc_valid_len)\n",
    "    \n",
    "    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n",
    "    dec_X = torch.unsqueeze(torch.tensor(\n",
    "        [tgt_vocab['<bos>']], dtype=torch.long, device=device), dim=0) # 把<bos>包装成tensor，注意形状\n",
    "    output_seq, attention_weight_seq = [], []\n",
    "    for _ in range(num_steps):\n",
    "        Y, dec_state = net.decoder(dec_X, dec_state)\n",
    "        dec_X = Y.argmax(dim=2) # 预测值作为下一步输入\n",
    "        pred = dec_X.squeeze(dim=0).type(torch.int32).item()\n",
    "        if save_attention_weights: # 注意力机制，这里用不到\n",
    "            attention_weight_seq.append(net.decoder.attention_weights)\n",
    "        if pred == tgt_vocab['<eos>']:\n",
    "            break\n",
    "        output_seq.append(pred)\n",
    "    return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e59efaf",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "BLEU的代码实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "69d2be34",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:48:32.836209Z",
     "iopub.status.busy": "2022-07-31T02:48:32.835769Z",
     "iopub.status.idle": "2022-07-31T02:48:32.843280Z",
     "shell.execute_reply": "2022-07-31T02:48:32.842465Z"
    },
    "origin_pos": 51,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def bleu(pred_seq, label_seq, k):  \n",
    "    \"\"\"计算BLEU\"\"\"\n",
    "    pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n",
    "    len_pred, len_label = len(pred_tokens), len(label_tokens)\n",
    "    score = math.exp(min(0, 1 - len_label / len_pred))\n",
    "    for n in range(1, k + 1):\n",
    "        num_matches, label_subs = 0, collections.defaultdict(int)\n",
    "        for i in range(len_label - n + 1):\n",
    "            label_subs[' '.join(label_tokens[i: i + n])] += 1\n",
    "        for i in range(len_pred - n + 1):\n",
    "            if label_subs[' '.join(pred_tokens[i: i + n])] > 0:\n",
    "                num_matches += 1\n",
    "                label_subs[' '.join(pred_tokens[i: i + n])] -= 1\n",
    "        score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n",
    "    return score"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2bef6de",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "将几个英语句子翻译成法语"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e14cbf1c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-07-31T02:48:32.846215Z",
     "iopub.status.busy": "2022-07-31T02:48:32.845747Z",
     "iopub.status.idle": "2022-07-31T02:48:32.871911Z",
     "shell.execute_reply": "2022-07-31T02:48:32.871265Z"
    },
    "origin_pos": 53,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "go . => va !, bleu 1.000\n",
      "i lost . => j'ai perdu ., bleu 1.000\n",
      "he's calm . => il est riche est riche aucune demande faire tomber tomber, bleu 0.258\n",
      "i'm home . => je suis en <unk> tomber ., bleu 0.473\n"
     ]
    }
   ],
   "source": [
    "engs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\n",
    "fras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\n",
    "for eng, fra in zip(engs, fras):\n",
    "    translation, attention_weight_seq = predict_seq2seq(\n",
    "        net, eng, src_vocab, tgt_vocab, num_steps, device)\n",
    "    print(f'{eng} => {translation}, bleu {bleu(translation, fra, k=2):.3f}')"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "rise": {
   "autolaunch": true,
   "enable_chalkboard": true,
   "overlay": "<div class='my-top-right'><img height=80px src='http://d2l.ai/_static/logo-with-text.png'/></div><div class='my-top-left'></div>",
   "scroll": true
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "vscode": {
   "interpreter": {
    "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
